package lib

import (
	"RMS/app/shop/model"
	"RMS/common"
	"RMS/common/cache"
	"context"
	"github.com/go-basic/uuid"
	jsoniter "github.com/json-iterator/go"
	"strconv"
)

func ImplAddCart(ctx context.Context, req *model.AddCartReq) *model.AddCartResp {
	resp := &model.AddCartResp{}
	detail := make(map[string]interface{})
	if err := jsoniter.Unmarshal([]byte(req.Detail), &detail); err != nil {
		resp.Status = common.ErrCode
		resp.Message = common.JsonErrMessage
		return resp
	}
	amount := int64(req.Amount)
	detail["amount"] = amount
	b, _ := jsoniter.Marshal(detail)
	if Uuid, ok := cache.CacheMap[req.Detail]; ok {
		key := cache.GetCartKey(ctx, strconv.FormatInt(int64(req.Id), 10))
		if amount == 0 {
			_, err := cache.RDB.HDel(ctx, key, Uuid).Result()
			if err != nil {
				resp.Status = common.ErrCode
				resp.Message = common.AddErrMessage
				return resp
			}
			delete(cache.CacheMap, req.Detail)
		} else {

			_, err := cache.RDB.HSet(ctx, key, Uuid, string(b)).Result()
			if err != nil {
				resp.Status = common.ErrCode
				resp.Message = common.AddErrMessage
				return resp
			}
		}
	} else if amount > 0 {
		uuid := uuid.New()
		key := cache.GetCartKey(ctx, strconv.FormatInt(int64(req.Id), 10))
		_, err := cache.RDB.HSet(ctx, key, uuid, string(b)).Result()
		if err != nil {
			resp.Status = common.ErrCode
			resp.Message = common.JsonErrMessage
			return resp
		}
		cache.CacheMap[req.Detail] = uuid
	}

	resp.Status = common.SuccessCode
	resp.Message = common.SuccessMessage
	return resp
}
